from typing import List, Optional
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.models import CrawlingTask
from .interfaces import PlatformAdapter, NormalizedContent
from .normalizer import save_normalized_contents


async def run_crawling_task(session: AsyncSession, task_id: str, adapters: dict[str, PlatformAdapter], time_start: Optional[str], time_end: Optional[str], accounts: Optional[dict] = None, keywords: Optional[List[str]] = None) -> int:
    q = await session.execute(select(CrawlingTask).where(CrawlingTask.task_id == task_id))
    task = q.scalars().first()
    if not task:
        return 0
    adapter = adapters.get(task.platform) if adapters else None
    if not adapter:
        return 0
    contents: List[NormalizedContent] = []
    if keywords:
        contents.extend(await adapter.search_by_keywords(keywords, time_start, time_end))
    accs = []
    if accounts and isinstance(accounts.get(task.platform), list):
        accs = [str(x) for x in accounts.get(task.platform)]
    if accs:
        contents.extend(await adapter.fetch_by_accounts(accs, time_start, time_end))
    await save_normalized_contents(session, task.topic_code, task.task_id, contents)
    return len(contents)
